package com.example.helpconnect;

import java.util.List;

import com.facebook.Session;
import com.google.android.maps.OverlayItem;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.controller.*;
import com.example.model.UserCRUD;

public class HomePageActivity extends FragmentActivity {
	Button offeredSrvBtn;
	Button requestedSrvBtn;
	Button searchBtn;
	Button settingsBtn;
	Button checkInBtn;
	Button logOutBtn;

	User user;
    Context activityContext;
	static String currentLocation = new String();
	static Double latitude = 0.0;
	static Double longitude = 0.0;
	static LocationObtainer locTool;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_page);		

    	//Add these two lines to disable StrictMode
    	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    	StrictMode.setThreadPolicy(policy); 
		activityContext = HomePageActivity.this;
		LocationManager gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	LocationManager networkLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	
		locTool = new LocationObtainer(gpsLocationManager, networkLocationManager);
		
		Intent i = getIntent();
		i.getStringExtra("key");
		int userID = i.getIntExtra("userID", -1);
		user = new User(new UserCRUD());
		
		user = user.read(userID);
		
		checkInBtn = (Button)findViewById(R.id.checkInBtn);
		
		checkInBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
            	//locTool = new LocationObtainer(gpsLocationManager, networkLocationManager);
            	Location loc = locTool.getCurrentLocation();
            	currentLocation = loc.getLatitude() + ", " + loc.getLongitude();
            	latitude = locTool.getLatitude();
            	longitude = locTool.getLongitude();
            	
            	user.setLatitude(latitude);
            	user.setLongitude(longitude);
            	AlertDialog.Builder dialog = new AlertDialog.Builder(activityContext);
            	//update user with new location
            	try{
                    
                    dialog.setTitle("Check-In");
                    dialog.setMessage("You have successfully checked in and updated your location.");
                    dialog.setNegativeButton("Close", null);
                    
            		user.update();
            		
            	}
            	catch(Exception e){
            		e.printStackTrace();
            		dialog.setMessage("There was an error while checking in. Please try again later.");
            	}
            	finally{
            		dialog.show();
            	}
            	
            	
            	//get user with updated values
            	user = user.read(user.getUserID());
            	
            }
        });
		
		offeredSrvBtn = (Button)findViewById(R.id.offeredSrvBtn);
		offeredSrvBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				onClickOfferedServices();
			}
		});
		
		
		logOutBtn = (Button)findViewById(R.id.logOutBtn);
		
		logOutBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) { onClickLogout(); }

			
        });
		
		settingsBtn =  (Button)findViewById(R.id.settingsBtn);
		settingsBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) { onClickSettings(); }

			
        });
		
		searchBtn =  (Button)findViewById(R.id.searchBtn);
		searchBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) { onClickSearch(); }

			
        });
		
	}
	
	private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
          //Starting a new Intent
            Intent logInPage = new Intent(getApplicationContext(), LoggingActivity.class);
            startActivity(logInPage);
            finish();
        }
    }
	
	private void onClickSearch() {
		Intent searchPage = new Intent(getApplicationContext(), GoogleMapsActivity.class);
		searchPage.putExtra("userID", user.getUserID());    	            
        startActivity(searchPage);
    }
	
	private void onClickOfferedServices() {
		Intent offeredServicesPage = new Intent(getApplicationContext(), OfferedServicesActivity.class);
		offeredServicesPage.putExtra("userID", user.getUserID());    	            
        startActivity(offeredServicesPage);
    }
	
	private void onClickSettings() {
		setContentView(R.layout.settings);
		
		final EditText settingsFirstName = (EditText) findViewById(R.id.editSettingsFirstNameField);
		settingsFirstName.setText(user.getFirstName());
		System.out.println("fn: " + user.getFirstName());
		final EditText settingsLastName = (EditText) findViewById(R.id.editSettingsLastNameField);
		settingsLastName.setText(user.getLastName());
		System.out.println("ln: " + user.getLastName());
		final EditText settingsEmail = (EditText) findViewById(R.id.editSettingsEmailField);
		settingsEmail.setText(user.getEmail());
		
		
		Button cancelSettingsBtn =  (Button)findViewById(R.id.SettingsCancelBtn);
		cancelSettingsBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) { 

            	Intent homePage = new Intent(getApplicationContext(), HomePageActivity.class);
	            homePage.putExtra("userID", user.getUserID());    	            
	            startActivity(homePage);
	            finish();
	            
            }		
        });
		
		Button saveSettingsBtn =  (Button)findViewById(R.id.saveSettingsButton);
		saveSettingsBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) { 
            	user.setFirstName(settingsFirstName.getText().toString());
            	user.setLastName(settingsLastName.getText().toString());
            	user.setEmail(settingsEmail.getText().toString());
            	
            	AlertDialog.Builder dialog = new AlertDialog.Builder(activityContext);
            	//update user with new location
            	try{
            		user.update();
            		
                    dialog.setTitle("Settings");
                    dialog.setMessage("You have successfully updated your settings.");
                    dialog.setNegativeButton("Close", new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							Intent homePage = new Intent(getApplicationContext(), HomePageActivity.class);
				            homePage.putExtra("userID", user.getUserID());    	            
				            startActivity(homePage);
				            finish();
							
						}
                    	
                    });
            		
            	}
            	catch(Exception e){
            		e.printStackTrace();
            		dialog.setMessage("There was an error while updating your settings. Please try again later.");
            	}
            	finally{
            		dialog.show();
            	}
            	
            	
	            
            }		
        });
		
    }
	
	/** Called when the user clicks the Requested Services button */
	public void openRequestedServices(View view) {
		Intent intent = new Intent(this, RequestedServices.class);
		intent.putExtra("userID", user.getUserID());
		startActivity(intent);
	}
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	// Restores UI states after rotation.
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

 // Stop receiving location updates whenever the Activity becomes invisible.
    @Override
    protected void onStop() {
        super.onStop();
    }
       
   

}
